using Koala.Pro.Core.Models;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Koala.Pro.Helpers;

public class FileUploadImagePathConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || !(value is FileUploadInfo))
        {
            return null;
        }
        if (value is FileUploadInfo fileUploadInfo && !string.IsNullOrEmpty(fileUploadInfo.SavePath))
        {
            try
            {
                string basePath = fileUploadInfo.BasePath;
                string text = fileUploadInfo.SavePath;
                if (!text.StartsWith('/') && !text.StartsWith('\\'))
                {
                    text = "/" + text;
                }
                string text2 = basePath + text;
                if (string.IsNullOrEmpty(basePath) || (!basePath.StartsWith("http://") && !basePath.StartsWith("https://")))
                {
                    text2 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), text2);
                }
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.UriSource = new Uri(text2);
                bitmapImage.EndInit();
                return bitmapImage;
            }
            catch
            {
                return null;
            }
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
